package com.dawnling.amapinfowindows;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

public class MainActivity extends Activity implements
        AMap.OnMapClickListener, GeocodeSearch.OnGeocodeSearchListener, AMapLocationListener, LocationSource, AMap.OnMarkerClickListener{

    private MapView mapView;
    private AMap mAmap;
    private Marker markerPoint;//中心点定位
    private GeocodeSearch geocoderSearch;
    //默认有数据的经纬度
    private double latitude ;
    private double longitude ;
    // 声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    // 我的位置监听器
    private OnLocationChangedListener mLocationChangeListener = null;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private MarkerOptions markerOption;
    private Marker growMarker;
    private float mapZoom;
    private LatLng mapTarget;
    //搜索范围的距离
    private String km = "8";
    private float getZoomB = 17f;
    private TextView rlSearchPoint;//在此区域搜索
    private Marker currentMarker;
    private LatLng myLatLng;
    //位置许可
    private int ACCESS_COARSE_LOCATION = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //判断是否授权权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            //已授权权限
        } else {
            //申请权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    ACCESS_COARSE_LOCATION);
        }
        mapView = findViewById(R.id.map);
        rlSearchPoint = findViewById(R.id.rlSearchPoint);
        initMap();
    }

    /**
     * 初始化map
     */
    private void initMap() {
        /* 初始化AMap对象 */
        if (mAmap == null) {
            mAmap = mapView.getMap();
            initMyLocation();
            geocoderSearch = new GeocodeSearch(this);
            geocoderSearch.setOnGeocodeSearchListener(this);
            mAmap.setOnMarkerClickListener(this);
            mAmap.setOnMapClickListener(this);
            mAmap.setInfoWindowAdapter(new InfoWinAdapter(this));
            //地图移动监听
            mAmap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {
                }
                @Override
                public void onCameraChangeFinish(CameraPosition cameraPosition) {
                    //设置放大缩小无效果
                    if (getZoomB != cameraPosition.zoom ){
                        getZoomB = cameraPosition.zoom;
                    }
                    rlSearchPoint.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    /**
     * 初始化我的定位
     */
    private void initMyLocation() {
        mAmap.setLocationSource(this);

        mAmap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);// logo位置
        mAmap.getUiSettings().setLogoBottomMargin(-26);//设置logo 不可见 标尺可见的间距 都不可见-50
        mAmap.getUiSettings().setScaleControlsEnabled(true);// 标尺开关
        mAmap.getUiSettings().setCompassEnabled(false);//是否显示指南针
        mAmap.getUiSettings().setMyLocationButtonEnabled(false); // 是否显示默认的定位图层按钮
        mAmap.getUiSettings().setZoomControlsEnabled(false);//设置放大缩小按钮不显示
//        mAmap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);//设置放大缩小按钮在右中位置
//        //设置系统默认小蓝点绘制
        mAmap.setMyLocationEnabled(true);
        //定位的小图标 默认是蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.mipmap.navi_map_gps_locked));
        //自定义精度范围的圆形边框宽度
//        myLocationStyle.strokeWidth(1);
//        myLocationStyle.strokeColor(VersionUtils.getColor(R.color.colorText777));
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        mAmap.setMyLocationStyle(myLocationStyle);

        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * func:获取屏幕中心的经纬度坐标
     */
    public LatLng getMapCenterPoint() {
        int left = mapView.getLeft();
        int top = mapView.getTop();
        int right = mapView.getRight();
        int bottom = mapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mapView.getX() + (right - left) / 2);
        int y = (int) (mapView.getY() + (bottom - top) / 2);
        Projection projection = mAmap.getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));
        return pt;
    }

    /**
     * 地上生长的Marker
     */
    private void startGrowAnimation() {
        if(growMarker != null) {
            Animation animation = new ScaleAnimation(0,1,0,1);
            animation.setInterpolator(new LinearInterpolator());
            //整个移动所需要的时间
            animation.setDuration(1000);
            //设置动画
            growMarker.setAnimation(animation);
            //开始动画
            growMarker.startAnimation();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        if(mLocationClient!=null){
            mLocationClient.stopLocation();
        }
        deactivate();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        if(mLocationClient!=null){
            mLocationClient.startLocation();
        }
        mAmap.moveCamera(CameraUpdateFactory.zoomTo(14));
    }

    @Override
    public void onSaveInstanceState(Bundle arg0) {
        super.onSaveInstanceState(arg0);
        mapView.onSaveInstanceState(arg0);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mLocationClient!=null){
            mLocationClient.onDestroy();
        }
        mapView.onDestroy();
    }

    //停止定位
    @Override
    public void deactivate() {
        mLocationChangeListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }

    //激活定位
    @Override
    public void activate(OnLocationChangedListener listener) {
        mLocationChangeListener = listener;
    }

    @Override
    public void onMapClick(LatLng arg0) {
        //这个是隐藏infowindow窗口的方法
        if(currentMarker.isInfoWindowShown()){
            currentMarker.hideInfoWindow();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        currentMarker = marker;
        if (mAmap != null) {
            //设置某个点不可点击弹窗
            if (marker.equals(markerPoint)) {
                return true;
            }
            if (marker.getPosition().equals(myLatLng)){
                return true;
            }
        }
        //false表示marker被点击后显示在屏幕中心,true则不会. 所以+下面两句话即可
        marker.showInfoWindow();
        mAmap.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
        return true;
    }

    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        RegeocodeAddress regeocodeAddress = result.getRegeocodeAddress();
        String formatAddress = regeocodeAddress.getFormatAddress();
        ToastUtils.showShort(formatAddress + "");
    }

    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
    }

    /**
     * 响应逆地理编码的批量请求
     */
    private void getAddresses() {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(getMapCenterPoint().latitude, getMapCenterPoint().longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        //异步查询
        geocoderSearch.getFromLocationAsyn(query);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                //获取纬度
                latitude = amapLocation.getLatitude();
                //获取经度
                longitude = amapLocation.getLongitude();
                amapLocation.getAccuracy();//获取精度信息
                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    isFirstLoc = false;
                    //设置缩放级别
                    mAmap.moveCamera(CameraUpdateFactory.zoomTo(getZoomB));
                    //将地图移动到定位点
                    myLatLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                    mAmap.moveCamera(CameraUpdateFactory.changeLatLng(myLatLng));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mLocationChangeListener.onLocationChanged(amapLocation);

                    //获取定位信息
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(amapLocation.getCountry() + "" + amapLocation.getProvince() + "" + amapLocation.getCity() + "" + amapLocation.getDistrict() + "" + amapLocation.getStreet() + "" + amapLocation.getStreetNum());
                    LogUtils.e(latitude + "/经度：" + longitude);
                    //动态经纬度
                }
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                LogUtils.e("定位失败AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    /**
     * 权限申请回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
